package com.cordershy.service;

import com.cordershy.mapper.debtMapper;
import com.cordershy.pojo.debt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class debtService {
    @Autowired
    debtMapper debtMapper;
    @Transactional
    public List<debt> selectAll(String username){
        List<debt> debts =debtMapper.selectAll( username);
        Collections.reverse(debts);
        return debts;
    }
    @Transactional
    @Cacheable(value = "redisCache",key = "'debtid'+#debtid")
    public debt selectById(int debtid){
        System.out.println("执行方法体");
        return debtMapper.select(debtid);
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'debtid'+#debt.debtid")
    public debt addDebt(debt debt){
        debtMapper.insert(debt);
        return  debt;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'debtid'+#debt.debtid")
    public debt updateDebt(debt debt){
        //类调用 不会去查询redis缓存
        debt temp = selectById(debt.getDebtid());
        if (temp!=null){
            debtMapper.update(debt);
        }else{
            return null;
        }
        return  debt;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CacheEvict(value = "accountCache",key = "'debtid'+#debtid")
    public int deleteDebt(int debtid){
       return debtMapper.delete(debtid);
    }
}
